package com.shark.rebirth;

import android.content.Intent;
import android.util.Log;

import com.shark.lib.rebirth.RebirthEnv;
import com.shark.lib.rebirth.RebirthService;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;


public class Service1 extends RebirthService {
    private static final String TAG = "Service1";
    protected Disposable mDisposable;
    private boolean needStartWorkService = false;

    @Override
    protected boolean needStartWorkService() {
        needStartWorkService = RebirthEnv.needStartDaemon(this);
        Log.d(TAG, "needStartWorkService --- " + needStartWorkService);
        return needStartWorkService;
    }

    @Override
    public Boolean isWorkRunning() {
        return mDisposable != null && !mDisposable.isDisposed();
    }

    @Override
    public void startWork() {
            Log.d(TAG, "startWork --- 开始服务");

            mDisposable = Observable
                    .interval(1, TimeUnit.SECONDS)
                    .doOnDispose(new Action() {
                        @Override
                        public void run() throws Exception {
                            Log.d(TAG, " -- doOnDispose ---  取消订阅 .... ");
                            mDisposable = null;
                        }
                    })
                    .subscribe(new Consumer<Long>() {
                        @Override
                        public void accept(Long aLong) throws Exception {
                            Log.d(TAG, "每 3 秒采集一次数据... count = " + aLong);
                            if (aLong > 0 && aLong % 18 == 0) {
                                Log.d(TAG, "   采集数据  saveCount = " + (aLong / 18 - 1));
                            }
                        }
                    });
    }

    @Override
    public void stopWork() {
        Log.d(TAG, "stopWork --- 停止服务" + mDisposable );
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
            Log.d(TAG, "stopWork --- 停止了工作服务");
        }
    }

    @Override
    public void onServiceKilled() {
        Log.d(TAG, "onServiceKilled --- 保存数据到磁盘");
    }


}
